package cn.lokei.gateway.entity.kafka;

import com.alibaba.fastjson.JSONObject;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class KafkaProducer implements ApplicationContextAware {

	private static ApplicationContext applicationContext; // Spring应用上下文环境

	@Autowired
	private KafkaTemplate<String, Object> kafkaTemplate;

	// 自定义topic
	public static final String TOPIC_TEST = "topic.navlange";

	//
	public static final String TOPIC_GROUP1 = "topic.group1";

	//
	public static final String TOPIC_GROUP2 = "topic.group2";

	/*
	 * 实现了ApplicationContextAware 接口，必须实现该方法；
	 * 通过传递applicationContext参数初始化成员变量applicationContext
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		KafkaProducer.applicationContext = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) throws BeansException {
		return (T) applicationContext.getBean(name);
	}

	public static <T> T getBean(Class<T> clazz) throws BeansException {
		return (T) applicationContext.getBean(clazz);
	}

	public void send(Object obj) {
		String obj2String = JSONObject.toJSONString(obj);
		log.info("准备发送消息为：{}", obj2String);
		// 发送消息
		try {
			ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(TOPIC_TEST, "hello kafka");
			future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
				@Override
				public void onFailure(Throwable throwable) {
					// 发送失败的处理
					log.info(TOPIC_TEST + " - 生产者 发送消息失败：" + throwable.getMessage());
				}

				@Override
				public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
					// 成功的处理
					log.info(TOPIC_TEST + " - 生产者 发送消息成功：" + stringObjectSendResult.toString());
				}
			});
		} catch (Exception e) {
			log.info(e.toString());
		}

	}
}